package com.rimi.shiro.realm;

import java.util.HashSet;
import java.util.Set;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rimi.bean.User;
import com.rimi.service.LoginService;
import com.rimi.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;



import javax.annotation.Resource;



public class MyShiroRealm extends AuthorizingRealm {

	//这里因为没有调用后台，直接默认只有一个用户("luoguohui"，"123456")
	//private static final String USER_NAME = "luoguohui";
	//private static final String PASSWORD = "123456";

	@Resource
	private LoginService loginService;


	private User getUserByName(String name){
		User user =null;
		//通过用户名查询对象
		user = loginService.getUserByName(name);
		if(user !=null){//判断通过用户名查询的对象是否为空
			return user;
		}else{
			//通过电话查询对象
			user = loginService.getUserByPhone(name);
		}
		return user;
	}

	/*
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Set<String> roleNames = new HashSet<String>();
		Set<String> permissions = new HashSet<String>();
		roleNames.add("administrator");//添加角色
		permissions.add("newPage.jhtml");  //添加权限
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
		info.setStringPermissions(permissions);
		return info;
	}


	/*
	 * 登录验证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {

		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		User user = getUserByName(token.getUsername());
		if(user.getUserName()!=null && !"".equals(user.getUserName())){//用户名是否存在
			return new SimpleAuthenticationInfo(user.getUserName(),user.getUserPs(), getName());//返回用户名和密码
		}else{
			throw new AuthenticationException();
		}

	}



}
